package com.fms.config;

import com.fms.util.JacksonObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableWebMvc
@EnableTransactionManagement
public class SpringMvcConfig implements WebMvcConfigurer {

    //允许跨域的配置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")//允许跨域的请求路径
                .allowedOrigins("http://localhost:5173")//允许跨域的 域名
                .allowedHeaders("*")//允许跨域的请求头
                .allowedMethods("POST","GET","DELETE","PUT","UPDATE","OPTIONS")//允许跨域的请求方式
                .allowCredentials(true)//允许携带cookie访问
                .maxAge(3600);//允许跨域的超时时间
    }

    //配置静态资源的访问路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:E:/picSource/");
    }

    //重写该方法，表示可以给spring容器注册一个自定义的消息转换器
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //构建一个将实体数据转为json数据的转化器，实质上spring默认使用的就是这个消息转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new JacksonObjectMapper());//在消息转换器中，添加自定义的转化器
        converters.add(0,converter);
    }
}
